<template>
  <yd-layout class="m-goods-detail-index">
    <!-- 顶部导航 -->
    <yd-navbar slot="navbar" height=".88rem" bgcolor="#fff" color="#444" fontsize=".3rem">
      <yd-navbar-back-icon slot="left" color="#666" @click.native="$router.back()"></yd-navbar-back-icon>
      <!-- tab -->
      <div slot="center">
        <span @click="onChangeTab('Goods')" :class="{active: curComponent == 'Goods'}">商品</span>
        <span @click="onChangeTab('Common')" :class="{active: curComponent == 'Common'}">评价</span>
      </div>
    </yd-navbar>

    <!-- 内容 -->
    <goods v-if="curComponent == 'Goods' && goodsInfo.id" 
      @emit-buy="buyShow = true" 
      @on-all-common="curComponent = 'Common'" 
      :goodsId="goodsId" 
      :goodsInfo="goodsInfo">
    </goods>
    <detail v-if="curComponent == 'Detail'" :goodsDetail="goodsInfo.goodsDetails"></detail>
    <common v-if="curComponent == 'Common'" :goodsId="goodsId"></common>

    <!-- toolbar -->
    <div slot="tabbar" class="m-goods-detail-tabbar">
      <div class="icon-box">
        <button @click="$router.push(`/`)"><yd-icon name="home-outline" size=".4rem"></yd-icon><br>首页</button>
        <button @click="onCollectGoods"><yd-icon :name="goodsInfo.goodsWhetherCollect == 1 ? 'like' : 'like-outline'" size=".4rem"></yd-icon><br>{{goodsInfo.goodsWhetherCollect == 1 ? '已收藏' : '收藏'}}</button>
        <button @click="$router.push(`/cart`)"><yd-icon name="shopcart-outline" slot="right" size=".34rem" color="#666" @click.native="$router.push('/cart')"></yd-icon><br>购物车</button>
      </div>
      <div class="buy-box">
        <button @click="buyShow = true">立即购买</button>
        <button @click="buyShow = true">加入购物车</button>
      </div>
    </div>

    <!-- 立即购买弹出 -->
    <yd-popup v-model="buyShow" position="bottom" height="auto">
      <header>
        <div class="img-box" v-show="buyShow">
          <img v-lazy="goodsInfo.goodsMainPhoto">
        </div>
        <div class="tit-box">
          <p>{{goodsInfo.goodsName}}</p>
          <strong>￥{{goodsInfo.goodsMainCurPrice | currency}}</strong>
        </div>
      </header>

      <div class="color-box">
        <div v-for="(inventery, key) in goodsInfo.goodsInvenDetail">
          <span>{{inventery.name}}</span>
          <div>
            <span class="spec" v-for="(spec, keyspec) in inventery.goodsSpecProperties" @click="selected(keyspec)" :class="{active: clicked == keyspec}">
              {{spec.value}}
            </span>
          </div>
        </div>
      </div>

      <div class="select-item">
        <div>
          <h3 class="buy-num">购买数量</h3>
          <w-spinner :max="goodsInfo.goods_inventory" :min="1" v-model="value" @input="onSpinner(value)"></w-spinner>
        </div>
      </div>

      <footer>
        <button @click="onAddCart">加入购物车</button>
        <button @click="onBuy">立即购买</button>
      </footer>
    </yd-popup>

  </yd-layout>
</template>

<script>
  import Goods from './goods'
  import Detail from './detail'
  import Common from './common'
  import { session } from 'util/storage'
  import { mapGetters, mapActions } from 'vuex'
  import { apiGoodsDetail, apiAddCart } from 'js/api'

  export default {
    data() {
      return {
        buyShow: false,
        goodsId: '',
        curComponent: 'Goods',
        goodsInfo: {},
        clicked: -1,
        value: 1
      }
    },
    created() {
      this.goodsId = this.$route.params.id
      if (!this.goodsId) {
        this.$toast('该商品不存在', () => {
          this.$router.back()
        })
        return
      }
      this.getGoodsDetail()
    },
    methods: {
      ...mapActions(['fetchCollectGoods', 'deleteCollectGoods']),

      // 获取商品详情
      getGoodsDetail() {
        apiGoodsDetail(this.goodsId, this.token).then(data => {
          this.goodsInfo = (data || {}).goods || {}
          this.goodsInfo.goodsMainPhoto = this.goodsInfo.goodsMainPhotoList[0]
          this.goodsInfo.goodsMainCurPrice = this.goodsInfo.goodsPrice
          this.$set(this.goodsInfo, 'goodsMainSelectCount', 0)
          this.$set(this.goodsInfo, 'goodsMainSelectPrice', 0)
          this.goodsInfo.goodsInvenDetail = data.lmja
        })
      },

      // 选中的tab
      selected(keyspec) {
        this.clicked = keyspec
      },
      // 切换头部导航
      onChangeTab(hash) {
        this.curComponent = hash
      },
      // 收藏商品
      onCollectGoods() {
        if (this.goodsInfo.goodsWhetherCollect == 1) {
          this.deleteCollectGoods({
            goodsList: {goods_id: [this.goodsId], access_token: this.token},
            callback: data => {
              this.$toast('已取消')
              this.goodsInfo.goodsWhetherCollect = 0
            }
          })
          return
        }
        this.fetchCollectGoods({
          goodsList: {favourite_source: '页面', goods_id: this.goodsId, access_token: this.token, goods_type: 0},
          callback: data => {
            this.$toast('收藏成功')
            this.goodsInfo.goodsWhetherCollect = 1
          }
        })
      },
      // 选择商品颜色规格
      onChangeColor(index, imgUrl) {
        this.curColorIndex = index
        this.goodsInfo.goodsMainPhoto = imgUrl
      },
      // 数量加减
      onSpinner(value) {
        // if (gsp.selectChecked && Number(gsp.specpropertyInventCount) >= Number(gsp.specpropertySmallCount)) {
        //   this.$toast(`最低起订${gsp.specpropertySmallCount}件`)
        //   gsp.selectCount = gsp.specpropertySmallCount
        //   gsp.selectChecked = false
        // }
        // if (gsp.selectCount == 0) {
        //   gsp.selectChecked = true
        // }
        debugger
        this._calcuTotalCount(value)
        // this._getPriceArea()
        // this._calcuTotalPrice()
      },
      // 立即购买
      onBuy() {
        let orderFormData = this._transformDataFormat()
        if (orderFormData) {
          session.set('orderFormData', orderFormData)
          this.$router.push('/cart/order')
        } else {
          this.$toast('未满足最低起订量')
        }
      },
      // 加入购物车
      onAddCart() {
        let cartOrderFormData = this._transformCartDataFormat()
        if (cartOrderFormData) {
          apiAddCart(cartOrderFormData).then(data => {
            this.$toast('加入购物车成功')
          })
        } else {
          this.$toast('未满足最低起订量')
        }
      },
      // 验证单个尺码规格是否超过库存数量和满足最小购买量
      _isBuyCountBySize(oSize) {
        if (oSize.selectCount > oSize.specpropertyInventCount) {
          this.$toast('不能超过库存量')
          oSize.selectCount = oSize.specpropertyInventCount
        } else if (oSize.selectCount < oSize.specpropertySmallCount) {
          this.$toast(`最低起订量${oSize.specpropertySmallCount}件`)
          oSize.selectCount = oSize.specpropertyInventCount
        }
      },
      // 计算总数量
      _calcuTotalCount(value) {
        this.goodsInfo.goodsMainSelectCount = value
      },
      // 计算总价格
      _calcuTotalPrice() {
        this.goodsInfo.goodsMainSelectPrice = this.goodsInfo.goodsMainSelectCount * this.goodsInfo.goodsMainCurPrice
      },
      // 根据所选数量获取价格区间
      _getPriceArea() {
        const totalCount = this.goodsInfo.goodsMainSelectCount
        const aCount = []
        let curIndex = 0
        this.goodsInfo.tierdPriceAll.forEach((tierd, index) => {
          aCount.push(tierd.count)
        })
        const len = aCount.length - 1
        aCount.forEach((item, i) => {
          const aNum = item.split('-')
          if (aNum.length == 2) {
            if (totalCount >= aNum[0] && totalCount <= aNum[1]) {
              curIndex = i
            } else if (totalCount > aCount[len].split('-')[1]) {
              curIndex = len
            }
          } else {
            curIndex = len
          }
        })
        this.goodsInfo.goodsMainCurPrice = this.goodsInfo.tierdPriceAll[curIndex].price
      },
      // 把选中的商品处理成新增订单需要的格式, retun 订单数据
      // _transformDataFormat() {
      //   // 需要发送的表单数据
      //   const orderFormInfo = {
      //     access_token: this.token,
      //     orderType: 'weixin',
      //     payType: 'online',
      //     transport: '快递',
      //     goodsTotalPrice: this.goodsInfo.goodsMainSelectPrice,
      //     goodsVoList: [
      //       {
      //         storeId: this.goodsInfo.storeId + '',
      //         goodsId: this.goodsInfo.id + '',
      //         msg: '',
      //         goodsName: this.goodsInfo.goodsName,
      //         goodsPrice: this.goodsInfo.goodsMainSelectPrice,
      //         fightGoodsEndTime: this.goodsInfo.fightGoodsEndTime,
      //         count: this.goodsInfo.goodsMainSelectCount,
      //         shipPrice: 0,
      //         goodsGsp: []
      //       }
      //     ]
      //   }
      //   this.goodsInfo.goodsInvenDetail.forEach((color, colorIndex) => {
      //     color.specpropertyList.forEach(gsp => {
      //       orderFormInfo.goodsVoList[0].goodsGsp.push({
      //         count: gsp.selectCount + '',
      //         price: parseFloat(gsp.selectCount) * parseFloat(this.goodsInfo.goodsMainCurPrice),
      //         nowPrice: this.goodsInfo.goodsMainCurPrice,
      //         goodsSpecName: ['顔色', '尺码'],
      //         goodsSpecContent: [color.specpropertyName, gsp.specpropertyName],
      //         cartGsp: `${color.specpropertyId},${gsp.specpropertyId}`
      //       })
      //     })
      //   })
      //   return orderFormInfo.goodsVoList[0].goodsGsp.length ? orderFormInfo : null
      // },
      // 把选中的商品新增购物车
      _transformCartDataFormat() {
        // 需要发送的表单数据
        const orderFormInfo = {
          access_token: this.token,
          goodsVo: []
        }
        this.goodsInfo.goodsInvenDetail.forEach((invent, colorIndex) => {
          orderFormInfo.goodsVo.push({
            id: this.goodsInfo.id + '',
            count: Number(this.value),
            use_integral: ''
          })
        })
        return orderFormInfo.goodsVo.length ? orderFormInfo : null
      }
    },
    computed: {
      ...mapGetters(['token'])
    },
    components: {
      Goods,
      Detail,
      Common
    }
  }
</script>

<style lang="scss">
  @import '../../scss/_flex.scss';
  .m-goods-detail-index {
    .yd-navbar-center {
      span {
        padding: .24rem .06rem;
        margin-right: .4rem;
        border-bottom: 2px solid transparent;
        transition: .1s;
        &.active {
          border-bottom-color: #f00385;
        }
        &:last-child {
          margin-right: 0;
        }
      }
    }
    .yd-popup-content {
      header {
        position: relative;
        height: 1.9rem;
        font-size: .26rem;
        color: #666;
        border-bottom: 1px solid #eee;
        .img-box {
          position: absolute;
          top: -.6rem;
          left: .3rem;
          width: 2.26rem;
          height: 2.26rem;
          border-radius: 6px;
          overflow: hidden;
          img {
            width: 100%;
            height: 100%;
          }
        }
        .tit-box {
          padding-left: 2.8rem;
          padding-top: .44rem;
          p {
            padding-bottom: .06rem;
          }
        }
      }
      button {
        width: 100%;
        height: .88rem;
        color: #fff;
        font-size: .3rem;
      }
      strong {
        color: #f00385;
      }
      em {
        color: #f00385;
      }
      .color-box {
        white-space: nowrap;
        padding: 0.2rem .2rem;
        overflow-x: auto;
        border-bottom: 1px solid #eee;
        margin-bottom: 0.2rem;
        .spec {
            border: 1px solid #ccc;
            padding: 0.15rem 0.6rem;
            &.active {
              color: #f00385;
              border-color: #f00385;
            }
          }
        span {
          display: inline-block;
          padding-bottom: .2rem;
        }
      }
      .select-item {
        @include flex();
        height: 1.2rem;
        padding: 0 .24rem;
        border-bottom: 1px solid #eee;
        .buy-num {
          padding-bottom: 0.2rem;
        }
      }
      .total-box {
        padding: .14rem .3rem;
        text-align: right;
        color: #666;
        font-size: .28rem;
        em {
          color: #f00385;
        }
      }
      footer {
        @include flex();
        button {
          &:nth-child(1) {
            background-color: #3FBFF0;
          }
          &:nth-child(2) {
            background-color: #ef5c6e;
          }
        }
      }
    }
  }
  .m-goods-detail-tab {
    &.tabs-container {
      .tabs-list {
        top: 0;
        left: 24%;
        right: 24%;
        height: .88rem;
        .tabs-titleLink {
          height: .88rem;
          line-height: .88rem;
        }
        .tabs-title .tabs-titleLink .cursor {
          width: 45%;
        }
      }
      .tabContent-wrap {
        padding-top: 0;
      }
    }
  }
  .m-goods-detail-tabbar {
    @include flex();
    position: relative;
    z-index: 15;
    height: 1rem;
    background: #fff;
    text-align: center;
    button {
      height: 100%;
      font-size: .2rem;
      color: #666;
    }
    .icon-box {
      width: 40%;
      height: 100%;
      border-top: 1px solid #eee;
      button {
        width: 31%;
        height: 100%;
      }
      .yd-icon-like {
        color: #f00385;
      }
    }
    .buy-box {
      width: 60%;
      height: 100%;
      button {
        width: 49%;
        font-size: .3rem;
        &:nth-child(2) {
          background: #ef5c6e;
          color: #fff;
        }
      }
    }
  }
</style>